import React, { Component } from 'react';
import {
    View,
    Image,
    StyleSheet,
    Text,
    TextInput,
    Alert
} from 'react-native';

import NccButton from '../components/Button';

import { NavigationScreenProp } from 'react-navigation';
import { scaleSize, scaleFontSize } from "../util/size";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import icons from '../util/icons';
import { request } from '../util';
import { utilValidCheck } from '../util/validCheck';
import { API_MAP, ROUTERMAP, TOAST_MESSAGE, Global } from '../util/constants';


interface Iprops {
    navigation: NavigationScreenProp<any, any>
}

interface Istate {
    username: string,
    password: string,
    verifyCodeStatus: string,
    verifyCode: string,
    inputName:string,
    verifyCodeTime: number,
}

const VERIFY_CODE_TIME = Global.verifyCodeTime;;
const VERIFY_CODE_TEXT = '获取验证码';

class Register extends Component<Iprops, Istate>{

    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            verifyCodeStatus: VERIFY_CODE_TEXT,
            verifyCode: '',
            inputName:'',
            verifyCodeTime: VERIFY_CODE_TIME,
        };
    }

    turnToBack = () => {
        // this.props.navigation.back();
        this.props.navigation.goBack();
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    };

    onUsernameChanged = (username) => {
        username = username.replace(/[^\d]+/, '');
        this.setState({username: username})
    };

    onPasswordChanged = (newPassword) => {
        console.log(newPassword);//运行后可以在输入框随意输入内容并且查看log验证！
        this.setState({password : newPassword});
    };

    onVerifyCodeChange = (value) => {
        this.setState({verifyCode: value});
    };

    updateVerifyCodeStatus = () => {
        let {verifyCodeTime} = this.state;
        if (verifyCodeTime === 0) {
            this.setState({verifyCodeStatus: VERIFY_CODE_TEXT, verifyCodeTime: VERIFY_CODE_TIME});
            return;
        } 
        verifyCodeTime --;
        this.setState({verifyCodeTime: verifyCodeTime, verifyCodeStatus: `重试 (${verifyCodeTime} s)`});
        setTimeout(() => {
            this.updateVerifyCodeStatus();
        }, 1000);
    }

    getVerifyCode = async () => {
        const {username, verifyCodeTime} = this.state;
        
        if (!utilValidCheck(username, 'mobile')) {
            return Alert.alert(TOAST_MESSAGE.INVALID_MOBILE);
        }

        if (verifyCodeTime < VERIFY_CODE_TIME) {
            return;
        }

        request(API_MAP.verifyCode, {
            method: 'post',
            data: {
                mobile: username,
                type: 'register'
            }
        }, false, (err, res) => {
            if (res.retCode == '00') {
                Alert.alert(res.data.code);
                this.updateVerifyCodeStatus();
            } else if (res.retCode == '03') {
                Alert.alert(res.retMsg);
            } else {
                Alert.alert(TOAST_MESSAGE.AGAIN_LATER);
            }
        })
    }

    register = () => {
        const {username, password, verifyCode} = this.state;

        if (!utilValidCheck(username, 'name')) {
            return Alert.alert(TOAST_MESSAGE.INVALID_MOBILE);
        }

        if (!utilValidCheck(password, 'password')) {
            return Alert.alert(TOAST_MESSAGE.INVALID_PASSWORD);
        }

        if (!utilValidCheck(verifyCode, 'verifyCode')) {
            return Alert.alert(TOAST_MESSAGE.INVALID_CODE);
        }

        request(API_MAP.register, {
            method: 'POST',
            data: {
                reg_name: username,
                reg_password: password,
                code: verifyCode
            }
        }, false, (err, res) => {
            if (err || res.retCode !== '00') {
                return Alert.alert(res.retMsg);
            }
            Alert.alert('注册成功');
            this.turnToPage(ROUTERMAP.login);
        });
    };


    render() {

        return (
            <View
            style={{
                display: 'flex',
                flex: 1,
                backgroundColor: '#4869EE',
                flexDirection: 'column',
                //justifyContent: 'center',
                alignItems: 'center',
            }}>

                <View style={{ alignItems: 'flex-end', marginTop: scaleSize(52.8), marginLeft: scaleSize(291.8) }}>
                    <Text
                        onPress={() => this.turnToBack()}>
                        <Image source={icons.signClose} style={{
                            width: scaleSize(20),
                            height: scaleSize(20),
                        }} />
                    </Text>
                </View>
            
                <View
                    style={{ justifyContent: 'center', marginTop: scaleSize(53.9) }}>
                    <Image source={icons.signLogo}
                        style={{ width: scaleSize(98), height: scaleSize(102) }} />
                </View>
            
                <KeyboardAwareScrollView>

                <View style={{
                    display: 'flex',
                    flexDirection: 'row',
                    marginTop: scaleSize(50),
                }}>
                    {/* <TextInput
                        style={[styles.textInputStyle, { width: scaleSize(215), borderRightWidth: 0, borderBottomRightRadius: 0, borderTopRightRadius: 0 }]}
                        maxLength={11}
                        placeholder="中国大陆"
                        placeholderTextColor='white'
                        underlineColorAndroid={'transparent'}
                    /> */}
                    <View style={[styles.textInputStyle, { width: scaleSize(215), 
                        borderRightWidth: 0, borderBottomRightRadius: 0, borderTopRightRadius: 0 }]}/>
                    <View
                        style={{
                            width: scaleSize(80),
                            borderBottomRightRadius: 100,
                            borderTopRightRadius: 100,
                            borderColor: 'rgba(255,255,255,0.5)',
                            borderWidth: 1,
                            borderLeftWidth: 0,
                            height: scaleSize(48),
                        }}>


                        <Text style={{
                            color: '#FFFFFF',
                            textAlign: 'center',
                            lineHeight: scaleSize(48),
                            height: scaleSize(48),
                            fontSize: scaleFontSize(14),
                            letterSpacing: 1.49,
                            paddingRight: 22.5
                        }}> {'+86 >'}</Text>

                    </View>
                </View>

                <TextInput
                    onChangeText={this.onUsernameChanged}  //添加值改变事件
                    style={[styles.textInputStyle, { marginTop: 16 }]}
                    value={this.state.username}
                    maxLength={11}
                    placeholder="手机号码"
                    keyboardType='numeric'
                    placeholderTextColor='white'
                    underlineColorAndroid={'transparent'}
                />

                <TextInput
                    onChangeText={this.onPasswordChanged}  
                    style={[styles.textInputStyle, { marginTop: 16 }]}
                    maxLength={11}
                    placeholder="密码"
                    secureTextEntry={true}
                    placeholderTextColor='white'
                    underlineColorAndroid={'transparent'}
                />

                <View style={{
                    flexDirection: 'row',
                    marginTop: scaleSize(16),
                }}>

                    <TextInput
                        onChangeText = {this.onVerifyCodeChange}
                        maxLength={6}
                        placeholder="动态密码"
                        placeholderTextColor='white'
                        underlineColorAndroid={'transparent'}
                        style={[styles.textInputStyle2, {width: scaleSize(145),borderRightWidth: 0, 
                            borderBottomRightRadius: 0, borderTopRightRadius: 0 }]}
                    />

                    <View
                        style={{
                            width: scaleSize(150),
                            height: scaleSize(48),
                            borderBottomRightRadius: 100,
                            borderTopRightRadius: 100,
                            borderColor: 'rgba(255,255,255, 0.5)',
                            borderWidth: 1,
                            borderLeftWidth: 0,

                        }}>

                        <Text
                            onPress={() => { this.getVerifyCode() }}
                            style={{
                                color: '#FFFFFF',
                                textAlign: 'right',
                                lineHeight: scaleSize(48),
                                height: scaleSize(48),
                                fontSize: scaleFontSize(14),
                                paddingRight: 24,
                                letterSpacing: 1.49,
                            }}>{this.state.verifyCodeStatus}</Text>

                    </View>

                </View>


                <NccButton
                    onPress={this.register}
                    text={"注册"}
                    textStyle={styles.buttonStyle}
                    buttonStyle={{ backgroundColor: 'white', borderRadius: 100, marginTop: scaleSize(16), height: scaleSize(48) }}

                />
                </KeyboardAwareScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        alignItems: 'center'
    },
    textInputStyle: {
        width: scaleSize(295),
        height: scaleSize(48),
        borderColor: 'rgba(255,255,255,0.5)',
        borderWidth: 1,
        borderRadius: 100,
        fontFamily: 'PingFangSC-Regular',
        textAlign: 'left',
        color: 'white',
        fontSize: scaleFontSize(13),
        letterSpacing: 1.49,
        paddingLeft: 30,
    },
    textInputStyle2: {
        paddingLeft: 30,
        width: scaleSize(165),
        height: scaleSize(48),
        borderColor: 'rgba(255,255,255,0.5)',
        borderWidth: 1,
        borderRadius: 100,
        fontFamily: 'PingFangSC-Regular',
        textAlign: 'left',
        color: 'white',
        fontSize: scaleFontSize(13),
        letterSpacing: 1.49,
        borderRightWidth: 0,
    },
    buttonStyle: {
        width: scaleSize(295),
        height: scaleSize(48),
        lineHeight: scaleSize(48),
        color: '#4869EE',
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleFontSize(16),
        textAlign: 'center',

    }
});


export default Register;